package com.itaming.lycheeframework.core.filter;

import com.itaming.lycheeframework.core.properties.LycheeXssProperties;
import com.itaming.lycheeframework.core.request.XssHttpServletRequestWrapper;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;

/**
 * XSS过滤器
 *
 * @author A.Ming
 */
@RequiredArgsConstructor
public class XssFilter implements Filter {

    /**
     * XSS配置
     */
    private final LycheeXssProperties lycheeXssProperties;

    /**
     * 路径匹配器
     */
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 执行过滤
     *
     * @param request     ServletRequest
     * @param response    ServletResponse
     * @param filterChain FilterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // 放行
        if (shouldSkip(((HttpServletRequest) request).getServletPath())) {
            filterChain.doFilter(request, response);
            return;
        }

        filterChain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response);
    }

    /**
     * 是否放行
     *
     * @param path 路径
     * @return boolean
     */
    private boolean shouldSkip(String path) {
        if (!lycheeXssProperties.isEnabled()) {
            return true;
        }

        for (String pattern : lycheeXssProperties.getExcludePath()) {
            if (antPathMatcher.match(pattern, path)) {
                return true;
            }
        }

        return false;
    }

}
